package com.dolphin.apipassenger.service;

import com.dolphin.common.constant.CommonStatusEnum;
import com.dolphin.common.constant.TokenConstants;
import com.dolphin.common.dto.ResponseResult;
import com.dolphin.common.response.TokenResponse;
import com.dolphin.common.dto.TokenResult;
import com.dolphin.common.util.JwtUtils;
import com.dolphin.common.util.RedisPrefixUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class TokenService {

    @Autowired
    StringRedisTemplate  stringRedisTemplate;
    public ResponseResult refreshToken(String refreshTokenSrc) {
        //解析refreshtoken
        TokenResult refreshTokenResult = JwtUtils.checkToken(refreshTokenSrc);
        if (refreshTokenResult == null) {
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(),CommonStatusEnum.TOKEN_ERROR.getValue());
        }
        String phone = refreshTokenResult.getPhone();
        String identity = refreshTokenResult.getIdentity();

        //读取redis中的refreshToken
        String redisRefreshTokenKey = RedisPrefixUtils.generatorTokenKey(phone, identity, TokenConstants.REFRESH_TOKEN);
        String redisRefreshTokenStr = stringRedisTemplate.opsForValue().get(redisRefreshTokenKey);
        //校验refreshToken
        if (StringUtils.isBlank(redisRefreshTokenStr) || !refreshTokenSrc.trim().equals(redisRefreshTokenStr.trim())) {
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(),CommonStatusEnum.TOKEN_ERROR.getValue());
        }

        //生成双token
        String accessToken = JwtUtils.generatorToken(refreshTokenResult.getPhone(), refreshTokenResult.getIdentity(), TokenConstants.ACCESS_TOKEN);
        String refreshToken = JwtUtils.generatorToken(refreshTokenResult.getPhone(), refreshTokenResult.getIdentity(), TokenConstants.REFRESH_TOKEN);

        String redisAccessTokenKey = RedisPrefixUtils.generatorTokenKey(phone, identity, TokenConstants.ACCESS_TOKEN);
        stringRedisTemplate.opsForValue().set(redisAccessTokenKey,accessToken,30, TimeUnit.DAYS);
        stringRedisTemplate.opsForValue().set(redisRefreshTokenKey,refreshToken,31, TimeUnit.DAYS);

        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken);
        tokenResponse.setRefreshToken(refreshToken);
        return ResponseResult.success(tokenResponse);
    }
}
